export const _toString = Object.prototype.toString
/**
 * 获取数据类型
 */
export function dataType(val: any): string {
  return _toString.call(val).slice(8, -1).toLowerCase()
}
export function isAsyncFunction(fn: any) {
  return dataType(fn) === 'asyncfunction'
}

export class LRUCache {
  size
  cache
  constructor(size?: string | number) {
    this.size = typeof size === 'number' ? size : Infinity
    this.cache = new Map()
  }

  /**
   *
   * 获取值
   */
  get(key: any) {
    const value = this.cache.get(key)

    if (!value) return null

    // 删除后重新设置
    this.cache.delete(key)
    this.cache.set(key, value)
    return value
  }

  /**
   *
   * 覆盖最老的
   */
  set(key: any, value: any) {
    // 超过最大值后移除旧的
    if (this.cache.size >= this.size && !this.cache.get(key)) {
      const firstKey = this.cache.keys().next().value

      this.cache.delete(firstKey)
    }
    this.cache.set(key, value)
  }

  remove(key: any) {
    this.cache.delete(key)
  }

  print() {
    for (const [key, value] of this.cache) {
      console.log(`${key} => ${value}`)
    }
  }

  clear() {
    this.cache.clear()
  }
}
const lruCache = new LRUCache(1000)
export function url2queryObj(url: string) {
  const query = lruCache.get(url)
  if (query) return query

  const res = url?.split('&').reduce((obj, item) => {
    const [key, val] = item.split('=')
    obj[key] = val
    return obj
  }, {} as Record<string, any>)
  lruCache.set(url, res)
  return res
}
